
#include "re2/re2.h"

extern "C"
{

int re2FullMatch(const char *target, const char *pattern)
{
	return RE2::FullMatch(target, pattern);
}

int re2PartialMatch(const char *target, const char *pattern)
{
	return RE2::PartialMatch(target, pattern);
}

int re2Match(const char *target, const char *pattern, int *start, int *len)
{
	RE2 regex(pattern);
	re2::StringPiece s;
	if ( !regex.Match(target, 0, RE2::UNANCHORED, &s, 1) ) return 0;
	*start = s.data()-target;
	*len = s.length();
	return 1;
}

int re2MatchSub(const char *target, const char *pattern, int *start, int *len, int n)
{
	RE2 regex(pattern);
	re2::StringPiece s[n];
	if ( !regex.Match(target, 0, RE2::UNANCHORED, s, n) ) return 0;
	for (int i = 0; i < n; i++) {
		if (s[i]!=NULL) {
			start[i] = s[i].data()-target;
			len[i] = s[i].length();
		} else {
			start[i] = -1;
			len[i] = 0;
		}
	}
	return 1;
}

RE2 *re2CreateRegEx(const char *pattern)
{
	RE2 *regex = new RE2(pattern);
	if (regex->ok()) return regex;
	return (RE2*) 0;
}

void re2FreeRegEx(RE2 *regex)
{
	delete regex;
}

int re2FullMatchRe(const char *target, RE2 *regex)
{
	return RE2::FullMatch(target, *regex);
}

int re2PartialMatchRe(const char *target, RE2 *regex)
{
	return RE2::PartialMatch(target, *regex);
}

int re2MatchRe(const char *target, RE2 *regex, int *start, int *len)
{
	re2::StringPiece s;
	if ( !regex->Match(target, 0, RE2::UNANCHORED, &s, 1) ) return 0;
	*start = s.data()-target;
	*len = s.length();
	return 1;
}

int re2MatchSubRe(const char *target, RE2 *regex, int *start, int *len, int n)
{
	re2::StringPiece s[n];
	if ( !regex->Match(target, 0, RE2::UNANCHORED, s, n) ) return 0;
	for (int i = 0; i < n; i++) {
		if (s[i]!=NULL) {
			start[i] = s[i].data()-target;
			len[i] = s[i].length();
		} else {
			start[i] = -1;
			len[i] = 0;
		}
	}
	return 1;
}

}
